<template>

  <div>
    <data-table ref="pagingTable" :options="options" :list-query="listQuery">
      <template #filter-content>

        <el-input v-model="listQuery.params.title" placeholder="搜索考试名称" style="width: 200px;"
                  class="filter-item"/>

      </template>

      <template #data-columns>

        <el-table-column label="考试名称" prop="title" show-overflow-tooltip/>

        <el-table-column label="考试次数" prop="tryCount" align="center"/>

        <el-table-column label="最高分" prop="maxScore" align="center"/>

        <el-table-column label="是否通过" align="center">

          <template v-slot="scope">
            <span v-if="scope.row.passed" style="color: #00ff00;">通过</span>
            <span v-else style="color: #ff0000;">未通过</span>
          </template>

        </el-table-column>

        <el-table-column label="最后考试时间" prop="updateTime" align="center"/>

        <el-table-column label="操作" align="center">
          <template v-slot="scope">
            <el-button type="primary" size="mini" icon="el-icon-view" @click="handleExamDetail(scope.row.examId)">
              详情
            </el-button>

            <el-button type="warning" size="mini" icon="el-icon-close" @click="handlerExamBook(scope.row.examId)">
              错题
            </el-button>

            <!-- ✅ 仅当通过时显示生成二维码按钮 -->
            <el-button v-if="scope.row.passed" type="success" size="mini" icon="el-icon-qrcode"
                       @click="generateQrCode(scope.row)">
              二维码
            </el-button>
          </template>
        </el-table-column>

      </template>

    </data-table>

    <el-dialog :visible.sync="dialogVisible" title="考试明细" width="60%">

      <div class="el-dialog-div">
        <my-paper-list :exam-id="examId" :user-id="userId"/>
      </div>

    </el-dialog>
    <el-dialog
      title="二维码信息"
      :visible.sync="qrCodeDialogVisible"
      width="600px"
    >
      <div style="text-align: center">
        <qrcode-vue
          ref="qrCode"
          :value="qrCodeContent"
          :size="300"
          render-as="canvas"
        />
        <el-button type="primary" style="margin-top: 20px" @click="printQrCode">
          打印二维码
        </el-button>
      </div>
    </el-dialog>


  </div>

</template>

<script>

import DataTable from '@/components/DataTable'
import MyPaperList from './paper'
import {mapGetters} from 'vuex'
import {applyExamList} from '@/api/paper/exam'
import QrcodeVue from 'qrcode.vue'

export default {
  name: 'MyExamList',
  components: {MyPaperList, DataTable, QrcodeVue},
  data() {
    return {
      qrCodeDialogVisible: false,
      qrCodeContent: '',
      loading: false,
      dialogVisible: false,
      examId: '',

      listQuery: {
        current: 1,
        size: 10,
        params: {
          title: ''
        }
      },

      options: {
        // 可批量操作
        multi: false,
        // 列表请求URL
        listUrl: '/exam/api/user/exam/my-paging'
      }
    }
  },
  computed: {
    ...mapGetters([
      'userId'
    ])
  },
  methods: {
    printQrCode() {
      this.$nextTick(() => {
        var canvas = null
        if (this.$refs.qrCode && this.$refs.qrCode.$el) {
          canvas = this.$refs.qrCode.$el.querySelector('canvas')
        }

        if (!canvas) {
          this.$message.error('二维码尚未加载完成')
          return
        }

        const dataUrl = canvas.toDataURL('image/png')
        const imgHtml = `<img src="${dataUrl}" style="width:300px;height:300px;" />`
        // const textHtml = `<p style="margin-top: 20px; white-space: pre-wrap;">${this.qrCodeContent.replace(/\n/g, '<br/>')}</p>`

        const printWindow = window.open('', '_blank')
        printWindow.document.open()
        printWindow.document.write(`
      <html>
        <head>
          <title>打印二维码</title>
          <style>
            body { text-align: center; font-family: Arial, sans-serif; padding-top: 50px; color: #333; }
            @media print {
              body { margin: 0; }
              img { max-width: 100%; }
            }
          </style>
        </head>
        <body>
          ${imgHtml}

        </body>
      </html>
    `)
        printWindow.document.close()

        // ✅ 等待窗口渲染完成后再打印
        printWindow.onload = () => {
          printWindow.focus()
          printWindow.print()
          printWindow.close()
        }
      })
    },
    generateQrCode(row) {
      const listQuery = {
        current: 1,
        size: 10,
        params: {
          userName: this.$store.state.user.name
        }
      }

      this.loading = true

      applyExamList(listQuery).then(res => {
        const {records} = res.data
        if (records && records.length > 0) {
          const userInfo = records[0]

          // 把重要信息做 URL 编码，避免特殊字符导致链接问题
          const params = new URLSearchParams({
            userId: userInfo.id,
            examId: row.examId,
            realName: userInfo.realName,
            phone: userInfo.phone,
            idCard: userInfo.idCard,
            companyName: userInfo.companyName,
            jobType: userInfo.jobType,
            workArea: userInfo.workArea,
            entryTime: userInfo.entryTime,
            leaveTime: userInfo.leaveTime,
            examTitle: row.title,
            passed: row.passed ? '通过' : '未通过',
            updateTime: row.updateTime,
            photoUrl: userInfo.photoUrl  // 照片链接
          })
          const baseUrl = process.env.VUE_APP_BASE_API.replace(/\/$/, '') // 去掉结尾的斜杠
          this.qrCodeContent = `${baseUrl}/qrcode-info.html?${params.toString()}`
          // 生成二维码内容：带参数的 URL，改成你自己的域名或者本地IP+端口
          // this.qrCodeContent = `http://192.168.0.105:9527/qrcode-info.html?${params.toString()}`
          this.qrCodeDialogVisible = true

        } else {
          this.$message.warning('未获取到用户信息')
        }
      }).catch(() => {
        this.$message.error('获取用户信息失败')
      }).finally(() => {
        this.loading = false
      })
    }
    ,
// generateQrCode(row) {
//   const listQuery = {
//     current: 1,
//     size: 10,
//     params: {
//       userName: this.$store.state.user.name
//     }
//   }

//   this.loading = true

//   applyExamList(listQuery).then(res => {
//     const { records } = res.data
//     if (records && records.length > 0) {
//       const userInfo = records[0]
//       // const baseUrl = process.env.VUE_APP_BASE_API
//       // const link = `${baseUrl}/qrcode-info.html?userId=${userInfo.id}&examId=${row.examId}`
//       const link = `http://192.168.0.105:9527/qrcode-info.html?userId=${userInfo.id}&examId=${row.examId}`

//       // ✅ 替换这里为链接
//       // const link = `http://your-domain.com/qrcode-info.html?userId=${userInfo.id}&examId=${row.examId}`
//       this.qrCodeContent = link
//       this.qrCodeDialogVisible = true
//     } else {
//       this.$message.warning('未获取到用户信息')
//     }
//   }).catch(() => {
//     this.$message.error('获取用户信息失败')
//   }).finally(() => {
//     this.loading = false
//   })
// },

//     generateQrCode(row) {
//       // 查询条件
//       const listQuery = {
//         current: 1,
//         size: 10,
//         params: {
//           userName: this.$store.state.user.name
//         }
//       }

//       this.loading = true

//       applyExamList(listQuery).then(res => {
//         const { records } = res.data
//         if (records && records.length > 0) {
//           const userInfo = records[0]

//           // 组合信息内容
//           const content = `
// 姓名：${userInfo.realName}
// 手机号：${userInfo.phone}
// 身份证号：${userInfo.idCard}
// 公司：${userInfo.companyName}
// 工种：${userInfo.jobType}
// 工作区域：${userInfo.workArea}
// 入厂时间：${userInfo.entryTime}
// 离厂时间：${userInfo.leaveTime}
// 考试名称：${row.title}
// 是否通过：${row.passed ? '通过' : '未通过'}
// 考试时间：${row.updateTime}
//         `.trim()

//           // 保存内容用于弹窗展示二维码
//           this.qrCodeContent = content
//           this.qrCodeDialogVisible = true

//         } else {
//           this.$message.warning('未获取到用户信息')
//         }
//       }).catch(() => {
//         this.$message.error('获取用户信息失败')
//       }).finally(() => {
//         this.loading = false
//       })
//     },
    // 开始考试
    handleExamDetail(examId) {
      this.examId = examId
      this.dialogVisible = true
    },

    handlerExamBook(examId) {
      this.$router.push({name: 'BookList', params: {examId: examId}})
    }
  }
}
</script>

<style scoped>
.el-dialog-div {
  height: 60vh;
  overflow: auto;
  padding: 10px;
}
</style>
